package com.hl.redisdemo.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;

public class RedissonLockUtil {
    private static final Jedis jedis = new Jedis("localhost", 6379);

    /**
     * 可重入锁加锁
     * @param lockKey 锁的key
     * @param requestId 请求标识
     * @param expireTime 超时时间
     * @return 是否成功获取锁
     */
    public static boolean lock(String lockKey, String requestId, int expireTime) {
        return tryLock(lockKey, requestId, expireTime);
    }

    /**
     * 可重入锁解锁
     * @param lockKey 锁的key
     * @param requestId 请求标识
     * @return 是否成功释放锁
     */
    public static boolean unlock(String lockKey, String requestId) {
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(luaScript, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        Long RELEASE_SUCCESS = 1L;
        return RELEASE_SUCCESS.equals(result);
    }

    /**
     * 获取可重入锁
     * @param lockKey 锁的key
     * @param requestId 请求标识
     * @param expireTime 超时时间
     * @return 是否成功获取锁
     */
    public static boolean tryLock(String lockKey, String requestId, int expireTime) {
        SetParams params = new SetParams();
        params.nx().px(expireTime); // 设置nx和px参数，保证只在不存在该key时设置值，并设置过期时间
        String result = jedis.set(lockKey, requestId, params);
        return "OK".equalsIgnoreCase(result);
    }
}